package fun.yyds.config.websocket;

import fun.yyds.common.ResponseData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/data")
public class DataController {

    @Autowired
    private DataPushHandler dataPushHandler;

    // 存储WebSocket会话ID和用户标识的映射，实际应用中可以用更安全的方式
    private static final Map<String, String> USER_SESSION_MAP = new java.util.concurrent.ConcurrentHashMap<>();

    // 开始推送数据
    @PostMapping("/start")
    public ResponseData startPush(@RequestBody QueryParams params, HttpSession session) {
        try {
            // 查询初始数据（最多10000条）
            List<Data> initialData = new ArrayList<>(10000);
            for (int i = 0; i < 10000; i++) {
                Data data = new Data();
                data.setContent("" + i);
                data.setId(i);
                initialData.add(data);
            }
            // 开始推送
            dataPushHandler.startPush(session.getId(), params, initialData);
            return ResponseData.success("数据推送已开始");
        } catch (Exception e) {
            return ResponseData.fail("启动推送失败：" + e.getMessage());
        }
    }

    // 暂停推送数据
    @PostMapping("/pause")
    public ResponseData pausePush(@RequestHeader("Session-Id") String sessionId) {
        try {
            dataPushHandler.pausePush(sessionId);
            return ResponseData.success("数据推送已开始");
        } catch (Exception e) {
            return ResponseData.fail("暂停推送失败：" + e.getMessage());
        }
    }

    // 继续推送数据
    @PostMapping("/resume")
    public ResponseData resumePush(@RequestHeader("Session-Id") String sessionId) {
        try {
            dataPushHandler.resumePush(sessionId);
            return ResponseData.success("数据推送已开始");
        } catch (Exception e) {
            return ResponseData.fail("恢复推送失败：" + e.getMessage());
        }
    }

    // 用于WebSocket处理器注册会话ID和用户的映射
    public static void registerSession(String userId, String sessionId) {
        USER_SESSION_MAP.put(userId, sessionId);
    }

    // 获取用户的会话ID
    public static String getSessionIdByUser(String userId) {
        return USER_SESSION_MAP.get(userId);
    }
}
